<?php

function pcgbasename($param, $suffix=null) {
    if ($suffix) {
        $tmpstr = ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR)), DIRECTORY_SEPARATOR);
        if ((strpos($param, $suffix)+strlen($suffix))  ==  strlen($param)) {
            return str_ireplace( $suffix, '', $tmpstr);
        }
        else {
            return ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
        }
    }
    else {
        return ltrim(substr($param, strrpos($param, DIRECTORY_SEPARATOR) ), DIRECTORY_SEPARATOR);
    }
}

function Logger($file, $msg) {
    $out = date("Y-m-d H:i:s")."  ".$_SERVER['REMOTE_ADDR']."  ".$msg."\n";
    file_put_contents($file, $out, FILE_APPEND | LOCK_EX | FILE_USE_INCLUDE_PATH);
}

function GetTpl($file) {
    $tpl = file_get_contents($file.".tpl", FILE_USE_INCLUDE_PATH) or die ("<h1>Site is not available now. Try again later.</h1>");
    return $tpl;
}

function GetUsersDB($gl) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db($gl["sql_db"])
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    return $db;
}

function SendMail($gl, $to, $msg) {
/*
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "/usr/bin/sendemail -f ".$gl["mail"]." -t ".$to." -u \"".$gl["mail_subject"]."\" -m \"".$msg."\" -o message-content-type=text -o message-charset=\"".$gl["mail_charset"]."\"";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
*/
    // mail($to, $gl["mail_subject"], $msg, null,"-f" . $gl["mail"]);

    //- $subject = "?UTF-8?B?". base64_encode( $gl["mail_subject"] ). "?=";
    $subject = $gl["mail_subject"];

    mail( $to, $subject, $msg, "Content-Type: text/html; charset=UTF-8", "-f" . $gl["mail"] );
}

/* Сжатие страницы */
function CompressHtml($str) {
    $order = array("\r\n", "\n", "\r", "\t");
    $str = str_replace($order, " ", $str);
    $str = preg_replace("/ {2,}/", " ", $str);
    $str = str_replace("> <", "><", $str);
    return $str;
}

/* Генерация строки для активации нового пользователя */
function GenKey() {
    $symbols = "0123456789abcdefghijklmnopqrstuvwxyz";
    $length = mt_rand(50, 70);
    for ($i = 0; $i < $length; $i++) 
        $key .= $symbols[mt_rand(0, strlen($symbols) - 1)];
    return $key;
}

/* Проверка ключа на корректность */
function PregKey($key)
{
    return preg_match("/^[a-zA-Z0-9]{50,70}$/", $key);
}

/* Проверяем корректность Логина */
function PregLogin($gl, $str, &$msg) {
    if (!$str)
        $msg .= "Незаполнено поле &laquo;Логин&raquo;<br />";
    elseif (!preg_match("/^[a-zA-Z0-9_-]{4,12}$/", $str))
        $msg .= "Недопустимые символы в поле &laquo;Логин&raquo;<br />";
    else {
        $db = GetUsersDB($gl);
        $sql_result = mysql_fetch_row(mysql_query("SELECT * FROM ".$gl["sql_table"]." WHERE username=\"".$str."\""));
        mysql_close($db);
        if ($sql_result)
            $msg .= "Выбранный &laquo;Логин&raquo; уже используется<br />";
        else
            return TRUE;
    }
}

/* Проверяем корректность Мыла */
function PregEmail($gl, $str, &$msg) {
    if (!$str)
        $msg .= "Незаполнено поле &laquo;E-mail&raquo;<br />";
    elseif (!preg_match("/^([a-zA-Z0-9_\.-]+)@([a-zA-Z0-9_\.-]+)\.([a-z\.]{2,6})$/", $str))
        $msg .= "Недопустимые символы в поле &laquo;E-mail&raquo;<br />";
    else {
        $db = GetUsersDB($gl);
        $sql_result = mysql_fetch_row(mysql_query("SELECT * FROM ".$gl["sql_table"]." WHERE mail=\"".$str."\""));
        mysql_close($db);
        if ($sql_result)
            $msg .= "Выбранный &laquo;E-mail&raquo; уже используется<br />";
        else
            return TRUE;
    }
}

/* Проверяем корректность Пароля */
function PregPassword($str, &$msg) {
    if (!$str)
        $msg .= "Незаполнено поле &laquo;Пароль&raquo;<br />";
    elseif (strpbrk($str, ' '))
        $msg .= "Недопустимые символы в поле &laquo;Пароль&raquo;<br />";
    elseif ((strlen($str) < 6) or (strlen($str) > 12))
        $msg .= "Недопустимая длина пароля<br />";
    else
        return TRUE;
}

/* Проверяем корректность Капчи */
function PregCaptcha($str1, $str2, &$msg) {
    if (!$str1)
        $msg .= "Незаполнено поле &laquo;Защитный код&raquo;<br />";
    elseif ($str1 != $str2)
        $msg .= "Неверно заполнено поле &laquo;Защитный код&raquo;<br />";
    else
        return TRUE;
}

/* Форма Входа */
function LoginCheck($gl, $input) {
    $CaptchaOK = ($input["use_kcaptcha"] > 1) ? PregCaptcha($input["kcaptcha"], $input["keystring"]) : TRUE;
    if ($CaptchaOK) {
        if (($input["login"] == $gl["admin_user"]) and ($input["password"] == $gl["admin_password"]))
            return TRUE;
        else {    
            $db = GetUsersDB($gl);
            $sql_result = mysql_fetch_assoc(mysql_query("SELECT uid FROM ".$gl["sql_table"]." WHERE username=\"".$input["login"]."\" AND password=\"".$input["password"]."\" AND confirm=\"1\""));
            mysql_close($db);
            return $sql_result;
        }
    }
}

/* Проверка данных в форме Регистрации */
function RegCheck($gl, $input, &$output) {
    $output = NULL;
    if ((!$input["login"]) or
        (!$input["email"]) or
        (!$input["password"]) or
        (!$input["kcaptcha"]))
        $output .= "<b>Заполните все поля</b><br />";
    else {
        $LoginOK = PregLogin($gl, $input["login"], $output);
        $EmailOK = PregEmail($gl, $input["email"], $output);
        $PasswordOK = PregPassword($input["password"], $output);
        $CaptchaOK = PregCaptcha($input["kcaptcha"], $input["keystring"], $output);
        return ($LoginOK and $EmailOK and $PasswordOK and $CaptchaOK);
    }
}

/* Регистрация нового пользователя */
function RegDo($gl, $input) {
    $db = GetUsersDB($gl);
    $ActivationKey = GenKey();
    $sql_result = mysql_query("INSERT INTO ".$gl["sql_table"]." (username, password, homedir, mail, confirm_str) VALUES ('".$input["login"]."', '".$input["password"]."', '".$gl["ftp_dir"]."/".$input["login"]."', '".$input["email"]."', '".$ActivationKey."')");
    $sql_result2 = mysql_fetch_assoc(mysql_query("SELECT uid FROM ".$gl["sql_table"]." WHERE username=\"".$input["login"]."\""));
    $UserUID = $sql_result2["uid"];
    mysql_query("INSERT INTO quotalimits (name, bytes_in_avail) VALUES ('".$input["login"]."', '0')");
    mysql_close($db);
    if ($sql_result) {
        $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
        if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
            $UserPort = $UserUID + 10000;
            $User = $input["login"];
            $UserPassword = $input["password"];
            include('icecast.php');
            include('ices.php');
            include('perl.php');
            $UserFTP = $gl["ftp_dir"]."/".$input["login"];
            $IcecastConfig = $UserFTP."/".$gl["ftp_config_dir"]."/icecast".$UserUID.".xml";
            $IcesConfig = $UserFTP."/".$gl["ftp_config_dir"]."/ices".$UserUID.".conf";
            $PerlConfig = $UserFTP."/".$gl["ftp_config_dir"]."/ices.pm";
            $script = "
                mkdir -p $UserFTP/music $UserFTP/jingls $UserFTP/".$gl["ftp_config_dir"]."
                chown ".$gl["ftp_user"].":".$gl["ftp_group"]." $UserFTP -R
                chmod 555 $UserFTP -R
                chmod g+w  $UserFTP/music $UserFTP/jingls
                echo '$icecast_tpl' > $IcecastConfig
                echo '$ices_tpl' > $IcesConfig
                echo '$perl_tpl' > $PerlConfig
                chown nobody:nogroup $UserFTP/".$gl["ftp_config_dir"]." -R
                chmod 500 $UserFTP/".$gl["ftp_config_dir"]." -R
                su nobody -c \"icecast2 -c $IcecastConfig -b\"
                ";
            $stream = ssh2_exec($connection, $script);
            fclose($stream);
            $ActivationLink = "http://".$_SERVER['HTTP_HOST']."/?action=regdo&key=".$ActivationKey;
            $Mail = str_replace("{LINK}", $ActivationLink, file_get_contents("mail1.tpl", FILE_USE_INCLUDE_PATH));
            SendMail($gl, $input["email"], $Mail);
            return TRUE;
        }
    }
}

/* Активация учетки */
function ConfirmTry($gl, $key, &$output) {
    $db = GetUsersDB($gl);
    $sql_result = mysql_fetch_assoc(mysql_query("SELECT username, password, uid, mail FROM ".$gl["sql_table"]." WHERE confirm_str=\"".$key."\" AND confirm=\"0\""));
    if (!$sql_result) {
        mysql_close($db);
        return "no";
    }
    else {
        $sql_result2 = mysql_query("UPDATE ".$gl["sql_table"]." SET confirm=\"1\", confirm_str=\"".date("Y-m-d H:i:s")."\" WHERE username=\"".$sql_result["username"]."\"");
        mysql_close($db);
        if ($sql_result2) {
            $output["username"] = $sql_result["username"];
            $output["password"] = $sql_result["password"];
            $output["port"] = $sql_result["uid"] + 10000;
            $output["mail"] = $sql_result["mail"];
            return "yes";
        }
    }
}

/* Список активированных пользователей */
function ConfirmUsers($gl) {
    $db = GetUsersDB($gl);
    $sql_query = mysql_query("SELECT * FROM ".$gl["sql_table"]." WHERE confirm=\"1\" ORDER BY tariff");
    while($sql_result = mysql_fetch_assoc($sql_query))
        $result[] = $sql_result;
    mysql_close($db);
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $Table = "
<table>
    <tr>
        <th>#</th>
        <th>Логин</th>
        <th>Пароль / Email</th>
        <th>Дата регистрации</th>
        <th>FTP</th>
        <th>Тариф</th>
        <th>Истекает</th>
        <th>Icecast</th>
        <th>Ices</th>
        <th>Порт</th>
    </tr>";
        for ($i = 0; $i < count($result); $i++) {
    
            if ($result[$i]["shell"] == "/bin/false")
                $result[$i]["shell"] = "<img class=\"user\" src=\"/images/off.png\" alt=\"Закрыт\" />";
            elseif ($result[$i]["shell"] == "/bin/bash")
                $result[$i]["shell"] = "<img class=\"user\" src=\"/images/on.png\" alt=\"Открыт\" />";
  
            $result[$i]["tariff_name"] = $gl["TARIFF"][$result[$i]["tariff"]]["name"];
        
            if ($result[$i]["end_date"] == "0000-00-00")
                $result[$i]["end_date"] = "Не задано";
            else
                $result[$i]["end_date"] = date('d M Y',strtotime($result[$i]["end_date"]));

            $result[$i]["reg_date"] = date('d M Y',strtotime($result[$i]["reg_date"]));
    
            $result[$i]["port"] = 10000 + $result[$i]["uid"];
    
            $script = "ps aux | awk '{if(($11==\"icecast2\")&&($13~\"icecast".$result[$i]["uid"].".xml\")) print $2}' | xargs echo -n";
            $stream = ssh2_exec($connection, $script);
            $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
            stream_set_blocking($errorStream, true);
            stream_set_blocking($stream, true);
            $result[$i]["pid"] = !stream_get_contents($errorStream) ? stream_get_contents($stream) : NULL;
    
            $script = "ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$result[$i]["uid"].".conf\")) print $2}' | xargs echo -n";
            $stream = ssh2_exec($connection, $script);
            $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
            stream_set_blocking($errorStream, true);
            stream_set_blocking($stream, true);
            $result[$i]["pid2"] = !stream_get_contents($errorStream) ? stream_get_contents($stream) : NULL;

            $script = "du -sb ".$gl["ftp_dir"]."/".$result[$i]["username"]." | awk '{print $1}' | xargs echo -n";
            $stream = ssh2_exec($connection, $script);
            $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
            stream_set_blocking($errorStream, true);
            stream_set_blocking($stream, true);
            $result[$i]["hdd_used"] = round((!stream_get_contents($errorStream) ? stream_get_contents($stream) : NULL) / 1024 / 1024 / 1024, 2); /* в Gb */
            $result[$i]["hdd_per"] = @round(100 * $result[$i]["hdd_used"] / $gl["TARIFF"][$result[$i]["tariff"]]["hdd"]);

            $TRColor = ($i % 2) ? " class=\"next\"" : NULL;
            $Table .= "
    <tr".$TRColor.">
        <td>".$i."</td>
        <td>
            <b>".$result[$i]["username"]."</b>
            <br />
            <a href=\"/?action=del&amp;id=".$result[$i]["uid"]."\" title=\"Удалить\">
                <img class=\"user\" src=\"/images/delete.svg\" alt=\"Удалить\" /></a>
        </td>
        <td>
            ".$result[$i]["password"]."
            <br />
            ".$result[$i]["mail"]."
        </td>
        <td>".$result[$i]["reg_date"]."</td>
        <td>
            ".$result[$i]["hdd_used"]." Gb (".$result[$i]["hdd_per"]." %)
            <br />
            ".$result[$i]["shell"]."
        </td>
        <td>
            ".$result[$i]["tariff_name"]."
            <br />
            <a href=\"/?action=change&amp;id=".$result[$i]["uid"]."\" title=\"Сменить\">
                <img class=\"user\" src=\"/images/edit.svg\" alt=\"Сменить\" /></a>
        </td>
        <td>
            ".$result[$i]["end_date"]."
            <br/>
            <a href=\"/?action=extend&amp;id=".$result[$i]["uid"]."\" title=\"Продлить\">
                <img class=\"user\" src=\"/images/edit.svg\" alt=\"Продлить\" /></a>
        </td>
        <td>PID: ".$result[$i]["pid"]."<br />";
            $Table .= $result[$i]["pid"] ? "
            <img class=\"user\" src=\"/images/on.png\" alt=\"Запущен\" />
            <a href=\"/?action=stop&amp;id=".$result[$i]["uid"]."\" title=\"Остановить\">
                <img class=\"user\" src=\"/images/stop.svg\" alt=\"Остановить\" /></a>" : " 
            <img class=\"user\" src=\"/images/off.png\" alt=\"Не запущен\" />
            <a href=\"/?action=start&amp;id=".$result[$i]["uid"]."\" title=\"Запустить\">
                <img class=\"user\" src=\"/images/start.svg\" alt=\"Запустить\" /></a>";
            $Table .= "
        </td>
        <td>PID: ".$result[$i]["pid2"]."<br />";
            $Table .= $result[$i]["pid2"] ? "
            <img class=\"user\" src=\"/images/on.png\" alt=\"Запущен\" />
            <a href=\"/?action=stop2&amp;id=".$result[$i]["uid"]."\" title=\"Остановить\">
                <img class=\"user\" src=\"/images/stop.svg\" alt=\"Остановить\" /></a>" : "
            <img class=\"user\" src=\"/images/off.png\" alt=\"Не запущен\" />
            <a href=\"/?action=start2&amp;id=".$result[$i]["uid"]."\" title=\"Запустить\">
                <img class=\"user\" src=\"/images/start.svg\" alt=\"Запустить\" /></a>";
            $Table .= "
        </td>
        <td><a target=\"_blank\" href=\"http://".$_SERVER['HTTP_HOST'].":".$result[$i]["port"]."\">".$result[$i]["port"]."</td>
    </tr>";
            fclose($errorStream);
            fclose($stream);
        }
        $Table .= "
</table>";
        return $Table;
    }
}

/* Список неактивированных пользователей  */
function UnConfirmUsers($gl) {
    $db = GetUsersDB($gl);
    $sql_query = mysql_query("SELECT uid, username, mail, reg_date FROM ".$gl["sql_table"]." WHERE confirm=\"0\"");
    while($sql_result = mysql_fetch_assoc($sql_query))
        $result[] = $sql_result;
    mysql_close($db);
    $Table = "
<table>
    <tr>
        <th>#</th>
        <th>Логин</th>
        <th>Подтвердить</th>
        <th>Удалить</th>
        <th>Email</th>
        <th>Регистрация</th>
        <th>Дней прошло</th>
    </tr>";
    for ($i = 0; $i < count($result); $i++) {
        $RegTime = strtotime($result[$i]["reg_date"]);
        $CurTime = time();
        $result[$i]["timepass"] = round(bcdiv($CurTime - $RegTime, 86400)); /* дней без активации */

        $TRColor = ($i % 2) ? " class=\"next\"" : NULL;
        $Table .= "
    <tr".$TRColor.">
        <td>".$i."</td>
        <td><b>".$result[$i]["username"]."</b></td>
        <td>
            <a href=\"/?action=confirm&amp;id=".$result[$i]["uid"]."\" title=\"Активировать вручную\">
                <img class=\"user\" src=\"/images/apply.svg\" alt=\"Активировать\" /></a>
        </td>
        <td><a href=\"/?action=del&amp;id=".$result[$i]["uid"]."\" title=\"Удалить\">
                <img class=\"user\" src=\"/images/delete.svg\" alt=\"Удалить\" /></a>
        </td>
        <td>".$result[$i]["mail"]."</td>
        <td>".date('d M Y',strtotime($result[$i]["reg_date"]))."</td>
        <td>".$result[$i]["timepass"]."</td>
    </tr>";
    }
    $Table .= "
</table>";
    return $Table;
}

/* Наличие пользователя в БД */
function UserCheck($gl, $uid) {
    if (!$uid)
        return FALSE;
    $db = GetUsersDB($gl);
    $sql_result = mysql_fetch_assoc(mysql_query("SELECT username FROM ".$gl["sql_table"]." WHERE uid=\"".$uid."\""));
    mysql_close($db);
    return $sql_result["username"];
}

/* Мануальная активация пользователя */
function UserConfirm($gl, $uid) {
    $db = GetUsersDB($gl);
    $sql_result = mysql_query("UPDATE ".$gl["sql_table"]." SET confirm=\"1\", confirm_str=\"".date("Y-m-d H:i:s")." by admin\" WHERE uid=\"".$uid."\"");
    return $sql_result;
}

/* Удалить пользователя ($user передается, т.к. он уже вычеслен через user_check()) */
function UserDel($gl, $uid, $user) {
    if (!$user)
        return FALSE;
    $db = GetUsersDB($gl);
    mysql_query("DELETE FROM ".$gl["sql_table"]." WHERE uid=\"".$uid."\"");
    mysql_query("DELETE FROM quotalimits WHERE name=\"".$user."\"");
    mysql_query("DELETE FROM quotatallies WHERE name=\"".$user."\"");
    mysql_close($db);
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $user_ftp = $gl["ftp_dir"]."/".$user;
        $script = "
            ps aux | awk '{if(($11==\"icecast2\")&&($13~\"icecast".$uid.".xml\")) print $2}' | xargs kill -9
            ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$uid.".conf\")) print $2}' | xargs kill -9 
            rm -rf $user_ftp
            ";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
}

/* Информация о текущем тарифе */
function GetTariff($gl, $uid) {
    $db = GetUsersDB($gl);
    $sql_result = mysql_fetch_assoc(mysql_query("SELECT tariff FROM ".$gl["sql_table"]." WHERE uid=\"".$uid."\""));
    mysql_close($db);
    return $sql_result["tariff"];
}

/* Сменить тариф */
function UserTariffChange($gl, $uid, $tariff) {
    if (GetTariff($gl, $uid) == $tariff) 
        return "nochanged";
    elseif (in_array($tariff, array(0, 1, 2, 3, 4, 5, 6, 7, 8))) {
        $db = GetUsersDB($gl);
        $sql_result = mysql_fetch_assoc(mysql_query("SELECT username, password FROM ".$gl["sql_table"]." WHERE uid=\"".$uid."\""));
        $User = $sql_result["username"];
        $UserPassword = $sql_result["password"];
        $UserPort = $uid + 10000;
        if ($tariff == 0) {   
            include('icecast.php');
            mysql_query("UPDATE ".$gl["sql_table"]." SET tariff=\"".$tariff."\", shell=\"/bin/false\", end_date=\"0000-00-00\" WHERE uid=\"".$uid."\"");
        }
        else {
            include('icecast+.php');
            mysql_query("UPDATE ".$gl["sql_table"]." SET tariff=\"".$tariff."\", shell=\"/bin/bash\" WHERE uid=\"".$uid."\"");
        }
        mysql_query("UPDATE quotalimits SET bytes_in_avail=\"".$gl["TARIFF"][$tariff]["hdd_Bt"]."\" WHERE name=\"".$User."\"");
        mysql_close($db);
        $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
        if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
            IcecastStop($gl, $uid);
            $IcecastConfig = $gl["ftp_dir"]."/".$User."/".$gl["ftp_config_dir"]."/icecast".$uid.".xml";
            $script = "
                echo '$icecast_tpl' > $IcecastConfig
                chown nobody:nogroup $IcecastConfig
                chmod 500 $IcecastConfig
            ";
            $stream = ssh2_exec($connection, $script);
            fclose($stream);
            IcecastStart($gl, $uid, $User);
            return "changed";
        }
    }
}

/* Продлить пользователя */
function UserExtend($gl, $uid, $date) {
    $NewDate = date('Y-m-d',strtotime($date));
    $CurDate = date('Y-m-d');
    if ($NewDate <= $CurDate)
        return "nopreg";
    else {
        $db = GetUsersDB($gl);
        $sql_result = mysql_query("UPDATE ".$gl["sql_table"]." SET end_date=\"".$NewDate."\" WHERE uid=\"".$uid."\"");
        mysql_close($db);
        if ($sql_result)
            return "preg";
        else
            return FALSE;
    }
}

/* Пользовательская инфо */
function UserInfo($gl, $user) {
    $db = GetUsersDB($gl);
    $sql_result = mysql_fetch_assoc(mysql_query("SELECT * FROM ".$gl["sql_table"]." WHERE username=\"".$user."\""));
    mysql_close($db);
    if ((!$sql_result["end_date"]) or ($sql_result["end_date"] == "0000-00-00"))
        $sql_result["end_date"] = "Нет данных";
    if ($sql_result["shell"] == "/bin/false")
        $sql_result["shell"] = "Закрыт";
    elseif ($sql_result["shell"] == "/bin/bash")
        $sql_result["shell"] = "Открыт";
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "du -sb ".$gl["ftp_dir"]."/".$user." | awk '{print $1}' | xargs echo -n";
        $stream = ssh2_exec($connection, $script);
        $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
        stream_set_blocking($errorStream, true);
        stream_set_blocking($stream, true);
        $sql_result["hdd_used"] = round((!stream_get_contents($errorStream) ? stream_get_contents($stream) : NULL) / 1024 / 1024 / 1024, 2); /* в Gb */
        $sql_result["hdd_per"] = @round(100 * $sql_result["hdd_used"] / $gl["TARIFF"][$sql_result["tariff"]]["hdd"]);
        fclose($errorStream);
        fclose($stream);

        $script = "ps aux | awk '{if(($11==\"icecast2\")&&($13~\"icecast".$sql_result["uid"].".xml\")) print $2}' | xargs echo -n";
        $stream = ssh2_exec($connection, $script);
        $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
        stream_set_blocking($errorStream, true);
        stream_set_blocking($stream, true);
        $sql_result["icecast_pid"] = !stream_get_contents($errorStream) ? stream_get_contents($stream) : NULL;
        $sql_result["icecast"] = $sql_result["icecast_pid"] ? "Запущен" : "Остановлен";

        $script = "ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$sql_result["uid"].".conf\")) print $2}' | xargs echo -n";
        $stream = ssh2_exec($connection, $script);
        $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
        stream_set_blocking($errorStream, true);
        stream_set_blocking($stream, true);
        $sql_result["ices_pid"] = !stream_get_contents($errorStream) ? stream_get_contents($stream) : NULL;
        $sql_result["ices"] = $sql_result["ices_pid"] ? "Запущен" : "Остановлен";
    }
    else {
        $sql_result["hdd_used"] = "Нет данных";
        $sql_result["hdd_per"] = "Нет данных";
        $sql_result["icecast"] = "Нет данных";
        $sql_result["ices"] = "Нет данных";
    }
    $sql_result["port"] = $sql_result["uid"] + 10000;
    return $sql_result;
}

/* Остановить icecast2 */
function IcecastStop($gl, $uid) {
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "
            ps aux | awk '{if(($11==\"icecast2\")&&($13~\"icecast".$uid.".xml\")) print $2}' | xargs kill -9
            ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$uid.".conf\")) print $2}' | xargs kill -9
            ";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
}

/* Запустить icecast2 ($user передается, т.к. он уже вычеслен либо через UserCheck для админа, либо находится в переменной сессии для юзера) */
function IcecastStart($gl, $uid, $user) {
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "
            ps aux | awk '{if(($11==\"icecast2\")&&($13~\"icecast".$uid.".xml\")) print $2}' | xargs kill -9
            ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$uid.".conf\")) print $2}' | xargs kill -9
            su nobody -c \"icecast2 -c ".$gl["ftp_dir"]."/".$user."/".$gl["ftp_config_dir"]."/icecast".$uid.".xml -b\" > /tmp/log.1 2>&1
            ";
	//echo $script;
        if (GetTariff($gl, $uid) != 0)
            $script .= "
                cd /".$gl["ftp_dir"]."/".$user."/".$gl["ftp_config_dir"]." && ices -c ices".$uid.".conf -B
                ";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
}

/* Остановить ices */
function IcesStop($gl, $uid) {
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$uid.".conf\")) print $2}' | xargs kill -9";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
}

/* Запустить ices ($user передается, т.к. он уже вычеслен либо через UserCheck для админа, либо находится в переменной сессии для юзера) */
function IcesStart($gl, $uid, $user) {
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "
            ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$uid.".conf\")) print $2}' | xargs kill -9
            cd /".$gl["ftp_dir"]."/".$user."/".$gl["ftp_config_dir"]." && ices -c ices".$uid.".conf -B
            ";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
}

/* ices следующий трек */
function IcesNext($gl, $uid) {
    $connection = ssh2_connect($gl["serv_server"], $gl["serv_port"]);
    if (ssh2_auth_password($connection, $gl["serv_login"], $gl["serv_password"])) {
        $script = "ps aux | awk '{if(($11==\"ices\")&&($13==\"ices".$uid.".conf\")) print $2}' | xargs kill -USR1";
        $stream = ssh2_exec($connection, $script);
        fclose($stream);
        return TRUE;
    }
}

/* Проверить существование новости */
function IsNew($gl, $new) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_result = mysql_fetch_assoc(mysql_query("SELECT * FROM news WHERE link=\"".$new."\""));
    mysql_close($db);
    return $sql_result;
}

/* Добавить новость */
function AddNew($gl, $input) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_result = mysql_query("INSERT INTO news (title, text, date) VALUES ('". $input["title"]."', '".$input["text"]."', '".$input["date"]."')");
    if ($sql_result) {
        $curLink = mysql_fetch_array(mysql_query("SELECT MAX(link) FROM news"));
        mysql_close($db);
        return $curLink[0];
    }
    else {
        mysql_close($db);
        return FALSE;
    }
}

/* Обновить новость */
function EditNew($gl, $input, $link) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_result = mysql_query("UPDATE news SET title=\"". $input["title"]."\", text=\"".$input["text"]."\", date=\"".$input["date"]."\" WHERE link=\"".$link."\"");
    mysql_close($db);
    return $sql_result;
}

/* Удалить новость */
function DelNew($gl, $link) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    mysql_query("DELETE FROM news WHERE link=\"".$link."\"");
    mysql_close($db);
}

/* Вывести все новости (для админа) */
function GetNewsList($gl) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
            or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
            or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_query = mysql_query("SELECT * FROM news ORDER BY link desc");
    while($sql_result = mysql_fetch_assoc($sql_query))
            $result[] = $sql_result;
    mysql_close($db);
    $output = "";
    for ($i = 0; $i < count($result); $i++) {
        $output .= "
            <a href=\"/?action=ednew&new=".$result[$i]["link"]."\" title=\"Редактировать\"><img class=\"user\" src=\"/images/edit.svg\" /></a>
            <a href=\"/?action=delnew&new=".$result[$i]["link"]."\" title=\"Удалить\"><img class=\"user\" src=\"/images/delete.svg\" /></a>
            <a class=\"new\" href=\"/?action=news&new=".$result[$i]["link"]."\">".$result[$i]["title"]."</a>
            <br />";
    }
    return $output;
}

/* Вывести все новости (для главной) */
function GetNews($gl) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
            or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
            or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_query = mysql_query("SELECT * FROM news ORDER BY link desc"); 
    while($sql_result = mysql_fetch_assoc($sql_query))
            $result[] = $sql_result;
    mysql_close($db);
    $output = "";
    for ($i = 0; $i < count($result); $i++) {
        $output .= "
            <span>" . date("d.m.Y", strtotime($result[$i]["date"])) . "</span>
            <a href=\"/?action=news&amp;new=" . $result[$i]["link"] . "\">" . $result[$i]["title"] . "</a>
            <p>" . mb_substr(strip_tags(htmlspecialchars_decode(str_replace("{EOF}", "\n", $result[$i]["text"])), ENT_QUOTES), 0, 80, "utf-8") . " ...</p>";
        
    }
    return $output;
}

/* Проверить существование страницы */
function IsPage($gl, $page) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_result = mysql_fetch_assoc(mysql_query("SELECT * FROM pages WHERE link=\"".$page."\""));
    mysql_close($db);
    return $sql_result;
}

/* Добавить страницу */
function AddPage($gl, $input) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_result = mysql_query("INSERT INTO pages (link, title, text) VALUES ('". $input["link"]."', '".$input["title"]."', '".$input["text"]."')");
    mysql_close($db);
    return $sql_result;
}

/* Обновить страницу */
function EditPage($gl, $input, $link) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_result = mysql_query("UPDATE pages SET title=\"". $input["title"]."\", text=\"".$input["text"]."\" WHERE link=\"".$link."\"");
    mysql_close($db);
    return $sql_result;
}

/* Удалить страницу */
function DelPage($gl, $link) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
        or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
        or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    mysql_query("DELETE FROM pages WHERE link=\"".$link."\"");
    mysql_close($db);
}

/* Вывести все страницы (для админа) */
function GetPagesList($gl) {
    $db = mysql_connect($gl["sql_server"], $gl["sql_user"], $gl["sql_password"])
            or die ("<h3>Failed connection to database server.<h3><h4>".mysql_error()."</h4>");
    mysql_select_db("site_db")
            or die ("<h3>Failed connection to database.<h3><h4>".mysql_error()."</h4>");
    $sql_query = mysql_query("SELECT * FROM pages ORDER BY link desc");
    while($sql_result = mysql_fetch_assoc($sql_query))
            $result[] = $sql_result;
    mysql_close($db);
    $output = "";
    for ($i = 0; $i < count($result); $i++) {
        $output .= "
            <a href=\"/?action=edpage&page=".$result[$i]["link"]."\" title=\"Редактировать\"><img class=\"user\" src=\"/images/edit.svg\" /></a>
            <a href=\"/?action=delpage&page=".$result[$i]["link"]."\" title=\"Удалить\"><img class=\"user\" src=\"/images/delete.svg\" /></a>
            <a class=\"new\" href=\"/?action=".$result[$i]["link"]."\">".$result[$i]["link"]."</a>
            <br />";
    }
    return $output;
}


?>
